package com.poten.controller;




import com.alibaba.nacos.client.utils.StringUtils;
import com.github.wxpay.sdk.WXPayUtil;

import com.poten.mapper.CourseMapper;
import com.poten.mapper.OrderMapper;

import com.poten.pojo.Order;
import com.poten.pojo.TbPayLog;
import com.poten.service.PayService;
import com.poten.utils.HttpClient;
import com.poten.utils.WechatPayUtils;
import com.tencent.common.pojo.Result;
import com.tencent.common.pojo.StatusCode;

import com.tencent.pojo.Course;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信支付控制层
 */
@RestController
@RequestMapping("/wechat")
public class PayController {

    @Autowired
    PayService payService;
    @Resource
    CourseMapper courseMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @RequestMapping("/createTest")
    public String creatTest(){
        Order order = new Order();
        order.setOid(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order);
       return "OK";
    }



    /**
     * 根据课程ID添加商品订单
     * @return
     */

    @RequestMapping("/addOrder")
    public Result addOrder(@RequestParam("id")BigInteger id){
        Course course= courseMapper.getByCourseID(id);
        //添加订单信息
        Order order = new Order();
        order.setOid(UUID.randomUUID().toString().replace("-",""));
        order.setStates(0);
        order.setCreTime(LocalDateTime.now().toString());
        order.setName(course.getTitle());
        order.setPrice(course.getPrice().doubleValue());
        orderMapper.addOrder(order);
        return new Result(StatusCode.OK,"订单生成成功",true,order);
    }

    /**
     * 微信支付工具类
     * @param
     * @param request
     * @return
     */
    @RequestMapping("pay")
    public Map<String,Object> pay(@RequestBody String orderIdList[], HttpServletRequest request){

        Map<String,Object> map = new HashMap<String,Object>();
        String userId = request.getHeader("userId");
           userId="111";
        if(StringUtils.isBlank(userId)){
            map.put("msg","用户未登录");
            map.put("code","5000");
            return map;
        }
        Map<String,Object> returnMap = payService.pay(userId,orderIdList);

        return returnMap;
    }



    /**
     * 支付成功后，微信进行回调通知咱们代码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("notifyUrl")
    public String notifyUrl(HttpServletRequest request, HttpServletResponse response){


        Map<String, String> map = WechatPayUtils.getWechatNotifyData(request);
        String return_code = map.get("return_code");

        if(!return_code.equals("SUCCESS")) {
            System.err.println("微信回调成功SUCCESS");
            return WechatPayUtils.returnError();
        }
        boolean flag = payService.checkOderPay(map);
        if(!flag){
            return WechatPayUtils.returnError();
        }

        return WechatPayUtils.returnSuccess();

    }


    /**
     * 根据咱们支付日志表的id，调用微信支付，查询下用户到底支付了没有
     * @param payLogId
     * @return
     */
    @RequestMapping("orderquery")
    public Map<String,Object> orderquery(@RequestParam("payLogId")String payLogId){

        Map<String, Object> resultMap = new HashMap<String, Object>();
         //订单查询
       TbPayLog payLog= payService.getById(payLogId);

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appid", "wxab8acb865bb1637e");
        paramMap.put("mch_id", "11473623");
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("out_trade_no", payLogId);
        try {
            String generateSignedXml = WXPayUtil.generateSignedXml(paramMap, "2ab9071b06b9f739b950ddb41db2690d");
            String  url = "https://api.mch.weixin.qq.com/pay/orderquery";
            HttpClient client = new HttpClient(url);
            client.setHttps(true);
            client.setXmlParam(generateSignedXml);
            client.post();

            //3.获取结果
            String xmlResult = client.getContent();

            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xmlResult);
            System.out.println(xmlToMap.get("trade_state").toString()+"---axmlToMap======================"+xmlToMap);
            if(xmlToMap.get("trade_state").toString().equals("SUCCESS")){
                resultMap.put("status",2000);
                resultMap.put("msg","订单查询成功");
                resultMap.put("payLog",payLog);
                return resultMap;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.put("status",5000);
        resultMap.put("msg","订单查询失败");
        resultMap.put("payLog", payLog);
        return resultMap;
    }


}
